<template>
    <div class="manage-role">
        <div style="height: 35px">
            <el-form :model="searchForm" :inline="true" size="mini">
                <el-form-item label="name">
                    <el-input v-model="searchForm.name"></el-input>
                </el-form-item>
                <el-form-item label="code">
                    <el-input v-model="searchForm.code"></el-input>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="listRole">Search</el-button>
                    <el-button type="primary" @click="listRole">Refresh</el-button>
                    <el-button type="primary" @click="handleCreate">New</el-button>
                </el-form-item>
            </el-form>
        </div>
        <div class="manage-role-list">
            <el-table
                    @row-click="handleRowClick"
                    border
                    default-expand-all
                    highlight-current-row
                    :data="roleTable"
                    row-key="ukId"
                    height="500"
                    size="mini"
                    style="width: 100%"
                    :tree-props="{children: 'children', hasChildren: 'hasChildren'}">
                <el-table-column
                        prop="name"
                        label="name"
                        width="*">
                </el-table-column>
                <el-table-column
                        prop="code"
                        label="code"
                        width="150">
                </el-table-column>
                <el-table-column
                        prop="status"
                        label="status"
                        width="70">
                    <template slot-scope="scope">
                        <el-switch
                                @change="statusChange($event, scope.row.ukId)"
                                :value="scope.row.status != '1'"
                                active-color="#909399"
                                inactive-color="#67c23a">
                        </el-switch>
                    </template>
                </el-table-column>
                <el-table-column
                        prop="sort"
                        label="sort"
                        width="60">
                </el-table-column>
                <el-table-column
                        label="操作"
                        width="235">
                    <template slot-scope="scope">
                        <el-button
                                size="mini"
                                @click="handleEdit(scope.row)">编辑
                        </el-button>
                        <el-button
                                size="mini"
                                type="danger"
                                @click="handleDelete(scope.row.ukId)">删除
                        </el-button>
                        <el-button
                                size="mini"
                                type="danger"
                                @click="handleBinding(scope.row.ukId)">绑定用户
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>
        </div>
        <div class="manage-role-user">
            <el-table
                    border
                    highlight-current-row
                    row-key="ukId"
                    height="500"
                    size="mini"
                    :data="userTable"
                    style="width: 100%">
                <el-table-column
                        prop="account"
                        label="account"
                        width="*">
                </el-table-column>
                <el-table-column
                        prop="username"
                        label="username"
                        width="120">
                </el-table-column>
            </el-table>
        </div>
        <el-dialog title="角色管理" :visible.sync="showRoleForm" :close-on-click-modal="false">
            <el-row>
                <el-col :span="12">
                    <el-form ref="form" :model="roleForm" label-width="120px">
                        <el-form-item label="角色编码">
                            <el-input v-model="roleForm.code"></el-input>
                        </el-form-item>
                        <el-form-item label="角色名称">
                            <el-input v-model="roleForm.name"></el-input>
                        </el-form-item>
                        <el-form-item label="用户授权范围">
                            <el-select v-model="roleForm.authorization.userType" style="width: 100%">
                                <el-option label="当前用户" :value=1></el-option>
                                <el-option label="当前用户和指定用户" :value=11></el-option>
                            </el-select>
                            <el-select multiple v-model="roleForm.authorization.userIds" v-if="roleForm.authorization.userType === 11" style="width: 100%">
                                <el-option
                                        v-for="item in userList"
                                        :key="item.ukId"
                                        :label="item.account"
                                        :value="item.ukId">
                                </el-option>
                            </el-select>
                        </el-form-item>
                        <el-form-item label="机构授权范围">
                            <el-select v-model="roleForm.authorization.orgType" style="width: 100%">
                                <el-option label="当前机构" :value=1></el-option>
                                <el-option label="当前机构和子机构" :value=11></el-option>
                                <el-option label="指定机构" :value=2></el-option>
                            </el-select>
                            <tree-select
                                    multiple
                                    :flat="true"
                                    style="width: 100%"
                                    v-if="roleForm.authorization.orgType === 2"
                                    :showCount="true"
                                    :openOnClick="true"
                                    :defaultExpandLevel="3"
                                    noChildrenText="无下级机构"
                                    v-model="roleForm.authorization.orgIds"
                                    :options="orgTable"
                                    :normalizer="orgTableNormalizer">
                            </tree-select>
                        </el-form-item>
                        <el-form-item label="角色授权范围">
                            <el-select v-model="roleForm.authorization.roleType" style="width: 100%">
                                <el-option label="当前角色" :value=1></el-option>
                                <el-option label="当前角色和指定角色" :value=11></el-option>
                            </el-select>
                            <el-select multiple v-model="roleForm.authorization.roleIds" v-if="roleForm.authorization.roleType === 11" style="width: 100%">
                                <el-option
                                        v-for="item in roleTable"
                                        :key="item.ukId"
                                        :label="item.name"
                                        :value="item.ukId">
                                </el-option>
                            </el-select>
                        </el-form-item>
                        <el-input v-model="roleForm.password" v-if="roleForm.passwordType == '3'" style="width: calc(100% - 110px)"></el-input>
                        <el-form-item label="状态">
                            <el-select v-model="roleForm.status" placeholder="请选择状态" style="width: 100%">
                                <el-option
                                        v-for="item in this.$store.state.Pabu.dict.manage.STATUS.dictItems"
                                        :key="item.ukId"
                                        :label="item.name"
                                        :value="parseInt(item.value)">
                                </el-option>
                            </el-select>
                        </el-form-item>
                        <el-form-item label="排序">
                            <el-input v-model="roleForm.sort" type="number" min="0" max="90000"></el-input>
                        </el-form-item>
                        <el-form-item>
                            <el-button type="primary" @click="handleSave">保存</el-button>
                            <el-button @click="showRoleForm = false">取 消</el-button>
                        </el-form-item>
                    </el-form>
                </el-col>
                <el-col :span="12" style="height: 100%; overflow: auto">
                    <el-tree
                            ref="menuTree"
                            :data="menuTree"
                            show-checkbox
                            default-expand-all
                            node-key="ukId"
                            :props="menuTreeProps">
                    </el-tree>
                </el-col>
            </el-row>
        </el-dialog>
        <el-dialog title="绑定用户" :visible.sync="showRoleUserForm" :close-on-click-modal="false">
            <el-transfer
                    @change="handleChange"
                    filterable
                    v-model="roleUserForm.userIds"
                    :props="{
                      key: 'ukId',
                      label: 'username'
                    }"
                    :data="userList">
                <span slot-scope="{ option }">{{ option.account }} - {{ option.username }}</span>
            </el-transfer>
        </el-dialog>
    </div>
</template>

<script>
  import TreeSelect from '@riophae/vue-treeselect'
  import '@riophae/vue-treeselect/dist/vue-treeselect.css'

  import {bindRoleUser, deleteRole, listRole, saveRole, updateRoleStatus} from "../../../api/manage/role";
  import {listMenuTree} from "../../../api/manage/menu";
  import {listUser, listUserByRoleId} from "../../../api/manage/user";
  import {listOrgTree} from "../../../api/manage/org";

  export default {
    name: "Role",
    components: {TreeSelect},
    data () {
      return {
        showRoleForm: false,
        roleTable: [],
        menuTree: [],
        menuTreeProps: {
          children: 'children',
          label: 'name'
        },
        userTable: [],
        searchForm: {},
        roleForm: {
          authorization: {
            userType: 1,
            orgType: 1,
            roleType: 1
          }
        },
        showRoleUserForm: false,
        roleUserForm: {
          roleId: "",
          userIds: []
        },
        userList: [],
        orgTable: [],
        orgTableNormalizer (node) {
          if (!node.children.length) {
            delete node.children;
          }
          return {
            id: node.ukId,
            label: node.name
          }
        }
      }
    },
    methods: {
      handleCreate () {
        this.roleForm = {
          status: 1,
          menuIds: [],
          authorization: {
            userType: 1,
            orgType: 1,
            roleType: 1
          }
        }
        this.listUser()
        this.listOrgTree()
        this.listRole()
        this.listMenuTree()
        this.showRoleForm = true
      },
      handleEdit (row) {
        this.roleForm = row
        this.listMenuTree()
        this.showRoleForm = true
      },
      handleSave () {
        let checkedKeys = this.$refs.menuTree.getCheckedKeys();
        let halfCheckedKeys = this.$refs.menuTree.getHalfCheckedKeys();
        this.roleForm.menuIds = checkedKeys.concat(halfCheckedKeys);
        saveRole(this.roleForm).then(result => {
          this.listRole()
          this.showRoleForm = false
        }).catch(error => {
          console.log(error)
        })
      },
      handleDelete (ukId) {
        this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          deleteRole(ukId).then(result => {
            this.listRole()
            this.showRoleForm = false
            this.$message({
              type: 'success',
              message: '删除成功!'
            });
          }).catch(error => {
            console.log(error)
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });
        });
      },
      handleBinding (ukId) {
        this.roleUserForm.roleId = ukId
        this.listUser()
        this.roleUserForm.userIds = []
        listUserByRoleId(ukId).then(result => {
          result.data.users.forEach(item => {
            this.roleUserForm.userIds.push(item.ukId)
          })
        }).catch(error => {
          console.log(error)
        })
        this.showRoleUserForm = true
      },
      handleChange () {
        bindRoleUser(this.roleUserForm).then(result => {
          this.listRole()
        })
      },
      handleRowClick (row) {
        listUserByRoleId(row.ukId).then(result => {
          this.userTable = result.data.users
        }).catch(error => {
          console.log(error)
        })
      },
      statusChange (value, paginationId) {
        let status = value ? 0 : 1
        updateRoleStatus(paginationId, status).then(result => {
          this.listRole()
        }).catch(error => {
          console.log(error)
        })
      },
      listRole () {
        listRole(this.searchForm, 1, 30).then(result => {
          this.roleTable = result.data.roles.records
        }).catch(error => {
          console.log(error)
        })
      },
      listMenuTree () {
        listMenuTree(0).then(result => {
          this.menuTree = result.data.menuTree
          this.$nextTick(function () {
            this.setMenuTreeCheck(this.roleForm.menuIds)
          })
        }).catch(error => {
          console.log(error)
        })
      },
      setMenuTreeCheck (menuIds) {
        for (let menuId of menuIds) {
          let node = this.$refs.menuTree.getNode(menuId);
          if (node.childNodes == 0) {
            this.$refs.menuTree.setChecked(menuId, true)
          }
        }
      },
      listOrgTree () {
        listOrgTree("0").then(result => {
          this.orgTable = result.data.orgTree
        }).catch(error => {
          console.log(error)
        })
      },
      listUser () {
        listUser().then(result => {
          this.userList = result.data.users.records
        })
      }
    },
    created () {
      this.listRole()
    }
  }
</script>

<style>
    .manage-role {
        width: 100%;
        height: 100%;
    }

    .manage-role-list {
        width: calc(100% - 400px);
        height: calc(100% - 35px);
        float: left;
    }

    .manage-role-user {
        width: 400px;
        height: calc(100% - 35px);
        float: left;
    }

    /* element ui样式重写 */
    .manage-role > .manage-role-list > .el-table,
    .manage-role > .manage-role-user > .el-table {
        height: calc(100% - 35px) !important;
    }

    .manage-role > .manage-role-list > .el-table > .el-table__body-wrapper,
    .manage-role > .manage-role-user > .el-table > .el-table__body-wrapper {
        height: calc(100% - 35px) !important;
    }

    .manage-role .el-transfer-panel {
        width: calc((100% - 190px) / 2);
    }

</style>